<template>
    <view>
        <hj-loading :show="isInitLoad" v-if="isInitLoad" />
        <view class="page over-auto-y column" v-else>
            <hj-navbar title="订单详情" />
            <view class="flex-auto w100 over-auto-y">
                <!-- 头部订单状态信息 -->
                <DetailHead :orderDet="orderDet" @upData="timeEnd" />
                <!-- 酒店信息 -->
                <DetailHotel :info="hotelInfo" :orderDet="orderDet" />
                <!-- 订单信息 -->
                <DetailInfo :orderDet="orderDet" @onAmount="showAmountPopup = true" />
            </view>
            <!-- 底部按钮 -->
            <DetailFooter
                :orderDet="orderDet"
                :isInvoice="isInvoice"
                @editOrder="editOrder"
                @cancelOrder="cancelOrder"
                @plyOrder="plyOrder"
            />
            <!-- 取消原因选择弹窗 -->
            <CancelPopup v-model="showCancelPopup" @cancelSubmit="cancelSubmit" />
            <!-- 修改弹窗 -->
            <EditPopup v-model="showEditPopup" :order="orderDet" />
            <!-- 消费明细弹窗 -->
            <AmountDetails v-model="showAmountPopup" :orderDet="orderDet" />
        </view>
    </view>
</template>

<script setup>
/**
 * @description 订单详情
 * @author yinzhi
 * @date 2025-05
 */
import { onLoad, onShow, onUnload } from '@dcloudio/uni-app'
import { ref, defineComponent } from 'vue'
import { logger } from '@/utils/log.js'
import {
    getOrderDetailApi,
    cancelUnPayApi,
    cancelPayApi,
    getPayOrderApi
} from '@/libs/api/orderApi.js'
import { getHotelBaseInfoApi } from '@/libs/api/baseApi.js'

// 引入组件
import DetailFooter from './components/DetailFooter.vue'
import DetailHead from './components/DetailHead.vue'
import DetailHotel from './components/DetailHotel.vue'
import DetailInfo from './components/DetailInfo.vue'
import AmountDetails from './components/AmountDetails.vue'
import CancelPopup from '../order-list/components/CancelPopup.vue'
import EditPopup from '../order-list/components/EditPopup.vue'
defineComponent({
    components: {
        DetailFooter,
        DetailHead,
        DetailHotel,
        DetailInfo,
        CancelPopup,
        EditPopup,
        AmountDetails
    }
})
// 加载状态
const isInitLoad = ref(true)
// 取消原因弹窗显示
const showCancelPopup = ref(false)
// 修改弹窗
const showEditPopup = ref(false)
// 消费明细弹窗
const showAmountPopup = ref(false)
// 订单信息
const orderDet = ref({
    orderStatus: 5,
    checkInDate: '',
    checkOutDate: ''
})
// 订单编号
const orderNo = ref('')

// 修改订单
const editOrder = () => {
    showEditPopup.value = true
}

// 更新订单详情
const upData = async () => {
    uni.hideLoading()
    // 调用接口获取订单详情
    await getOrderDetail()
    uni.$emit('upOrderList', {
        orderNo: orderNo.value
    })
}

// 倒计时结束
const timeEnd = async () => {
    orderDet.value.orderStatus = 6
    uni.$emit('upOrderList', {
        orderNo: orderNo.value
    })
}

// 酒店信息
const hotelInfo = ref({})

// 获取酒店信息
const getHotelBaseInfo = async id => {
    try {
        const data = await getHotelBaseInfoApi({
            id: id
        })
        hotelInfo.value = data || {}
    } catch (error) {
        isInitLoad.value = false
        logger.error('[getHotelBaseInfoApi] 获取酒店详情失败:', error)
    }
}

// 获取订单详情
const getOrderDetail = async () => {
    try {
        const data = await getOrderDetailApi({
            orderNo: orderNo.value
        })
        orderDet.value = data || {}
        if (
            orderDet.value.orderStatus === 1 &&
            Number(orderDet.value.expectCancelTimeSeconds) <= 0
        ) {
            orderDet.value.orderStatus = 6
        }
        await getHotelBaseInfo(data.hotelId)
        isInitLoad.value = false
    } catch (error) {
        isInitLoad.value = false
        logger.error('[getOrderDetailApi] 获取订单详情失败:', error)
    }
}

// 未付款取消
const cancelUnPay = async () => {
    try {
        await cancelUnPayApi({
            orderNo: orderNo.value
        })
        uni.showToast({
            title: '取消成功',
            icon: 'none',
            mask: true
        })
        upData()
    } catch (error) {
        logger.error('[cancelPayApi] 取消未支付订单失败:', error)
    }
}

// 取消订单规则 判断订单是否支付，未支付可以直接取消，其他状态需要打开取消原因选择弹窗
const cancelOrder = () => {
    if (orderDet.value.orderStatus === 1) {
        uni.showModal({
            title: '取消订单',
            content: '确定取消当前订单吗？',
            success: res => {
                if (res.confirm) {
                    cancelUnPay()
                }
            }
        })
    } else {
        showCancelPopup.value = true
    }
}
// 取消弹窗取消的订单
const cancelSubmit = async data => {
    try {
        await uni.showLoading({
            title: '加载中...'
        })
        await cancelPayApi({
            orderNo: orderNo.value,
            cancelReason: data.cancelReason
        })
        await uni.hideLoading()
        await uni.showToast({
            title: '提交成功',
            icon: 'none',
            mask: true
        })
        await upData()
    } catch (error) {
        await uni.hideLoading()
        logger.error('[cancelPayApi] 取消订单失败:', error)
    }
}
// 微信支付api
const requestPayment = data => {
    uni.requestPayment({
        timeStamp: data.timeStamp,
        nonceStr: data.nonceStr,
        package: data.packageValue,
        signType: data.signType,
        paySign: data.paySign,
        success: res => {
            uni.showToast({
                title: '支付成功',
                icon: 'none'
            })
            upData()
        },
        fail: err => {
            uni.showToast({
                title: '取消支付',
                icon: 'none'
            })
        }
    })
}
// 支付订单
const plyOrder = async () => {
    try {
        const data = await getPayOrderApi({
            orderNo: orderNo.value,
            payBizType: 1, //1: 订单支付
            payWay: 1 //1: 微信支付
        })
        await requestPayment(data)
    } catch (error) {
        logger.error('[getPayOrderApi] 唤起支付失败: ', error)
    }
}

// 是否为发票详情跳转过来的页面
const isInvoice = ref(false)

// 初始化页面
onLoad(e => {
    // 从个人中心跳转的携带的参数 订单状态
    if (e.isInvoice) {
        isInvoice.value = true
    }
    if (e.orderNo) {
        orderNo.value = e.orderNo
        getOrderDetail()
    }
})

onShow(() => {
    // 先移除之前的监听器 防止重复监听
    uni.$off('upDataOrder')
    uni.$on('upDataOrder', data => {
        upData()
    })
})

// 页面卸载
onUnload(() => {
    uni.$off('upDataOrder')
})
</script>

<style scoped lang="scss">
.page {
    background: $uni-bg-color-grey;
}
:deep(.u-count-down__text) {
    color: #444 !important;
    font-size: 48rpx !important;
}
</style>
